package com.imau.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {

    private static SqlSession sqlSession;


    public static SqlSession getSqlSession() {
        if (sqlSession == null) {
            //1.读取配置
            String resource = "mybatis-config.xml";
            InputStream inputStream = null;
            try {
                inputStream = Resources.getResourceAsStream(resource);
                //2.创建SqlSessionFactory
                SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
                //3.创建SqlSession
                sqlSession = factory.openSession(true);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return sqlSession;
    }
}
